<template>
  <div class="page">
    <h2>home页面</h2>
    <div>{{ msg }} {{ userName }}</div>
    <el-button type="primary" round @click="changeName">切换vuex里的数据</el-button>
    <ul>
      <li v-for="item in newList" :key="item.index">{{ item.name }}</li>
    </ul>
    <hr />
    <el-button type="success" @click="getData">获取数据</el-button>
    <el-button type="success" @click="getText">点击获取经典语录</el-button>
    <h2 style="width: 300px; margin: 20px auto">{{ text }}</h2>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
export default {
  data() {
    return {
      msg: "你好",
    };
  },
  components: {},
  created() {
    // console.log(this);
    this.getText();
  },
  computed: {
    ...mapState(["userName", "list", "text"]),
    ...mapGetters(["newList"]),
  },
  methods: {
    ...mapActions([
      "setName", // 映射 this.setName() 为 this.$store.dispatch('setName')
      "getText",
    ]),
    ...mapMutations([
      "CHANGE_NAME", // 映射 this.CHANGE_NAME() 为 this.$store.commit('CHANGE_NAME')
    ]),
    getData() {
      //原生ajax
      let xhr = new XMLHttpRequest();
      xhr.open("get", "/aaa/get/data?name=ajax");
      xhr.send(null);
      xhr.onload = () => {
        console.log(xhr.responseText);
      };
      // xhr.onreadystatechange = function () {
      //   if (this.readyState != 4) return;
      //   console.log(this.status); //状态码
      //   console.log(this.responseText);
      // };

      //fetch
      fetch("/aaa/post/data", {
        method: "post",
        body: JSON.stringify({
          name: "fetch",
        }),
        headers: {
          "Content-Type": "application/json",
        },
      })
        .then((res) => res.json())
        .then((res) => {
          console.log(res);
        });

      //axios
      this.$axios.post("/aaa/post/data", { name: "axios" }).then((res) => {
        console.log(res);
      });
    },
    changeName() {
      let name = this.userName === "user" ? "zhang" : "user";
      // this.CHANGE_NAME(name);
      this.setName(name);
    },
  },
};
</script>

<style>

</style>
